<template>
  <div class="table-wrapper">
    <el-table 
      :data="tableData" 
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      :cell-style="{ textAlign: 'center' }"
      border>
      <el-table-column 
        label="咨询师" 
        width="120" 
        align="center">
    <template #default="scope">
      {{ counselorNames[scope.row.counselor_id] || '加载中...' }}
    </template>
  </el-table-column>
      <el-table-column 
        label="预约状态" 
        width="120" 
        align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.appointment_status)">
            {{ getStatusText(scope.row.appointment_status) }}
          </el-tag>
        </template>
      </el-table-column>
 
      <el-table-column 
        label="预约时间" 
        width="180" 
        align="center">
        <template #default="scope">
          <span>{{ appointmentTimes[scope.row.time_id] || '加载中...' }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        prop="remark" 
        label="备注" 
        min-width="160" 
        align="center" 
        show-overflow-tooltip />
      <el-table-column 
        label="操作" 
        width="180" 
        align="center"
        fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.appointment_status === 0 || scope.row.appointment_status === 5 || scope.row.appointment_status === 1"
            type="danger"
            link
            class="table-button"
            @click="handleCancel(scope.row)">
            取消预约
          </el-button>
          <el-button
            v-else
            type="primary"
            link
            class="table-button">
            无操作
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.Page"
        v-model:page-size="queryParams.Size"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import AppointmentInfoApi from '@/api/appointment_info'
import CounselorApi from '@/api/counselor'
import type { AppointmentInfo, QueryParams } from '@/api/appointment_info/types'
import { useUserInfoStore } from '@/stores/info'
import ScheduleApi from '@/api/schedual'

const userInfoStore = useUserInfoStore()
const tableData = ref<AppointmentInfo[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<QueryParams>({
  Page: 1,
  Size: 10,
  client_id: userInfoStore.userInfo.user_id,
  is_delete: 0
})

// 存储咨询师ID和名字的映射
const counselorNames = ref<{ [key: string]: string }>({})

// 存储时间段映射
const periodMap: Record<number, string> = {
  1: '8:00-8:50',
  2: '9:00-9:50',
  3: '10:00-10:50',
  4: '11:00-11:50',
  5: '14:00-14:50',
  6: '15:00-15:50',
  7: '16:00-16:50'
}

// 存储预约时间信息的缓存
const scheduleCache = ref<{ [key: string]: { date: string; period: number } }>({})

// 存储格式化后的预约时间
const appointmentTimes = ref<{ [key: string]: string }>({})

// 获取并格式化预约时间
const formatAppointmentTime = async (timeId: string) => {
  try {
    const response = await ScheduleApi.getSchedule(timeId)
    if (response.data && Array.isArray(response.data)) {
      scheduleCache.value[timeId] = {
        date: response.data[0].date || '',
        period: response.data[0].period || 0
      }
    }

    // 从缓存中获取数据
    const scheduleInfo = scheduleCache.value[timeId]
    if (!scheduleInfo) return '--'

    // 格式化日期
    const date = new Date(scheduleInfo.date)
    const formattedDate = date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })

    // 获取时间段
    const time = periodMap[scheduleInfo.period] || '--'
    
    return `${formattedDate} ${time}`
  } catch (error) {
    console.error('获取预约时间失败:', error)
    return '--'
  }
}

// 监听表格数据变化，更新预约时间
watch(() => tableData.value, async (newData) => {
  for (const row of newData) {
    if (row.time_id) {
      appointmentTimes.value[row.time_id] = await formatAppointmentTime(row.time_id)
    }
  }
}, { immediate: true })

// 获取咨询师名字
const getCounselorName = async (counselorId: string) => {
  try {
    if (!counselorNames.value[counselorId]) {
      const res = await CounselorApi.getUserCounselor(counselorId)
      if (res) {
        if(Array.isArray(res.data)){
          counselorNames.value[counselorId] = res.data[0].name || '未知咨询师'
        }
      }
    }
  } catch (error) {
    console.error('获取咨询师信息失败:', error)
    counselorNames.value[counselorId] = '未知咨询师'
  }
}

// 获取预约列表
const getAppointmentList = async () => {
  try {
    const res = await AppointmentInfoApi.getAppointments(queryParams)
    if (Array.isArray(res.data)) {
      tableData.value = res.data
      total.value = res.data.length

      // 获取所有预约时间
      for (const row of res.data) {
        if (row.time_id) {
          appointmentTimes.value[row.time_id] = await formatAppointmentTime(row.time_id)
        }
      }

      // 获取所有咨询师的名字
      const counselorIds = new Set(res.data.map(item => item.counselor_id))
      await Promise.all(Array.from(counselorIds).map(id => getCounselorName(id)))
    } else {
      ElMessage.error('获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  }
}

// 状态转换
const getStatusText = (status: number | undefined) => {
  switch (status) {
    case 0: return '待接受'
    case 1: return '已接受'
    case 2: return '已拒绝'
    case 3: return '已完成'
    case 4: return '咨询者请求取消'
    case 5: return '咨询师请求取消'
    case 6: return '已取消'
  }
}

const getStatusType = (status: number | undefined) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'danger'
    case 3: return 'success'
    case 4: return 'warning'
    case 5: return 'warning'
    case 6: return 'danger'
  }
}

// 取消预约
const handleCancel = async (row: AppointmentInfo) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个预约吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    if (!row.record_id) {
      ElMessage.error('预约记录ID不存在')
      return
    }
    const res = await AppointmentInfoApi.updateAppointment(row.record_id, {
      appointment_status: row.appointment_status === 1 ? 4 : 6
    })
    
    if (res) {
      ElMessage.success('取消预约成功')
      getAppointmentList()
    } else {
      ElMessage.error('取消预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  queryParams.Size = val
  queryParams.Page = 1
  getAppointmentList()
}

const handleCurrentChange = (val: number) => {
  queryParams.Page = val
  getAppointmentList()
}


onMounted(() => {
  getAppointmentList()
})
</script>

<style scoped>
.table-wrapper {
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin: 0 auto;
  width: 820px;
  box-sizing: border-box;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 0;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table--border) {
  border: 1px solid var(--el-table-border-color);
}

:deep(.table-button) {
  padding: 4px 0;
  height: auto;
  font-size: 14px;
}

:deep(.el-button--primary.is-link) {
  color: var(--el-color-primary);
}

:deep(.el-button--danger.is-link) {
  color: var(--el-color-danger);
}

:deep(.el-tag) {
  margin: 0 2px;
}

:deep(.el-table .cell) {
  padding: 8px;
  line-height: 1.5;
}

:deep(.el-pagination) {
  justify-content: center;
  margin-top: 16px;
}

/* 添加按钮间距 */
.table-button + .table-button {
  margin-left: 8px;
}

/* 按钮颜色 */
:deep(.el-button--success.is-link) {
  color: var(--el-color-success);
}
</style>